package com.ftz.examinationsystem.service.impl;

import com.ftz.examinationsystem.dao.UserMapper;
import com.ftz.examinationsystem.pojo.*;
import com.ftz.examinationsystem.service.UserService;
import com.ftz.examinationsystem.util.DateArrange;
import com.ftz.examinationsystem.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.*;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    /**
     * map集合中根据value获取key
     * @param map
     * @param value
     * @return
     */
    public static Object getKry(Map map, String value){
        Object key = null;
        for(Object getkey:map.keySet()){
            if(map.get(getkey).equals(value)){
                key=getkey;
            }
        }
        return key;
    }

    @Override
    public void saveAll(List<Student> list) {
        userMapper.saveAll(list);
    }

    @Override
    public List<Student> showAll(Page page) {
        return userMapper.showAll(page);
    }

    @Override
    public Long countStu(Page page) {
        return userMapper.countStu(page);
    }

    @Override
    public int addRoom(Room room) {
        return userMapper.addRoom(room);
    }

    @Override
    public List<Room> getRoomList(RoomQuery roomQuery) {
        return userMapper.getRoomList(roomQuery);
    }

    @Override
    public Long countRoomList(RoomQuery roomQuery) {
        return userMapper.countRoomList(roomQuery);
    }

    @Override
    public Room getRoomById(Integer id) {
        return userMapper.getRoomById(id);
    }

    @Override
    public void updateRoom(Room room) {
        userMapper.updateRoom(room);
    }

    @Override
    public void deleteRooms(String ids) {
        userMapper.deleteRooms(ids); //删除机房
        userMapper.updateStuStateByRoomId(ids); //修改在该机房考试的学生安排状态为未安排
        userMapper.deleteAllStuByRoomId(ids); //删除在该机房考试的学生信息
        userMapper.deleteAllByRoomId(ids);  //删除该机房考场信息
    }

    @Override
    public List<Student> showStu() {
        return userMapper.showStu();
    }

    @Override
    public void deleteStus() {
        userMapper.deleteStus();
    }

    @Override
    public List<String> queryRoomAddr() {
        return userMapper.queryRoomAddr();
    }

    @Override
    public List<Room> queryRoom() {
        return userMapper.queryRoom();
    }

    @Override
    public List<Map<Object, Object>> selectTime(String times, Integer roomid) {
        return userMapper.selectTime(times,roomid);
    }

    //根据机房号查询在哪个校区
    public int isCampus(Object id){
        List<Room> rooms = queryRoom();
        for(int i=0;i<rooms.size();i++){
            Room room = rooms.get(i);
            if(room.getRoomId().equals(id)){
                return room.getCampus();
            }
        }
        return 0;
    }

    @Override
    public List<String> arrangerRoom(ArrangeParam arrangeParam){
        /**
         * 考场分布表
         */
        List<ERorder> eRorderLists=new ArrayList<>(); //插入数据库的考场安排信息
        List<String> timeList=new ArrayList<>(); //考试时间分配
        //开始时间
        String starttime = arrangeParam.getStarttime();
        Date start1=DateUtils.convertString2Date("HH:mm:ss",starttime);
        //结束时间
        String endtime = arrangeParam.getEndtime();
        Date end1=DateUtils.convertString2Date("HH:mm:ss",endtime);
        Integer duration = arrangeParam.getDuration();  //持续时间
        Integer interval = arrangeParam.getInterval();  //间隔时间

        timeList=DateArrange.getIntervalTimeList(starttime,endtime,"12:30:00","13:30:00",duration,interval);

        Date am = DateUtils.convertString2Date("HH:mm:ss", "12:30:00");
        Date pm = DateUtils.convertString2Date("HH:mm:ss", "13:30:00");

        Date date = DateUtils.convertString2Date("yyyy-MM-dd", arrangeParam.getExamData());  //考试日期

        List<Integer> roomIdList=new ArrayList<>(); //可以分配考场的机房号
        List<Room> rooms = userMapper.queryRoom(); //查询机房信息
        HashMap<Integer, String> map = new HashMap<>(); //所有机房号和机房地址
        HashMap<Integer, Integer> map2 = new HashMap<>(); //所有机房号和机房人数
        //存储机房空闲时间，key是机房号，value是aempty和pempty
        MultiValueMap<Integer,Integer> valueMap1=new LinkedMultiValueMap<>();
        for(Room room:rooms){
            map.put(room.getRoomId(),room.getRoomAddr());
            map2.put(room.getRoomId(),room.getRoomCap());
            valueMap1.add(room.getRoomId(),room.getAempty());
            valueMap1.add(room.getRoomId(),room.getPempty());
        }

        String roomNum = arrangeParam.getRoomNum();  //获取前端传递的机房名字符串
        if(roomNum.equals("0")){
            Set<Integer> integers = map.keySet();
            for(Integer i:integers){
                roomIdList.add(i);
            }
        }else {
            String[] split = roomNum.split(",");
            for(int i=0;i<split.length;i++){
                if(map.containsValue(split[i])){
                    roomIdList.add((Integer) getKry(map,split[i]));
                }
            }
        }

        System.out.println("------输出roomIdList------");
        System.out.println(roomIdList);
        System.out.println("--------------------------");

        int e=0;
        List<String> roonname=new ArrayList<>();
        for(int n=0;n<roomIdList.size();n++){
            List<Map<Object, Object>> mapList = selectTime(arrangeParam.getExamData(), roomIdList.get(n));
            System.out.println(mapList);
            if(mapList.get(0)==null){
                e++;continue;
            }
            Date a = DateUtils.convertString2Date("HH:mm:ss", String.valueOf(mapList.get(0).get("开始")));
            Date b = DateUtils.convertString2Date("HH:mm:ss", String.valueOf(mapList.get(0).get("结束")));
            if(end1.getTime()<=a.getTime()||start1.getTime()>=b.getTime()){
               e++;
            }else {
                Room room = getRoomById(roomIdList.get(n));
                roonname.add(room.getRoomAddr());
            }
        }
        System.out.println(e);
        if(e==0) return roonname;

        //存储考试的每场考试时间段,key是机房号，value是开始和结束时间
        MultiValueMap<Integer, String> valueMap = new LinkedMultiValueMap<>();
        int k=0;
        for(int i=0;i<timeList.size();i=i+2){
            valueMap.add(k,timeList.get(i));
            valueMap.add(k,timeList.get(i+1));
            k++;
        }

        System.out.println("--------输出valueMap--------");
        System.out.println(valueMap);
        System.out.println("----------------------------");

        //每个校区未安排考生
        int Hcount=userMapper.countStustate(arrangeParam.getCourse(),0,1);
        int Zcount=userMapper.countStustate(arrangeParam.getCourse(),0,2);
        int Tcount=userMapper.countStustate(arrangeParam.getCourse(),0,3);
        List<Integer> Hid=new ArrayList<>();
        List<Integer> Zid=new ArrayList<>();
        List<Integer> Tid=new ArrayList<>();
        for(int i=0;i<roomIdList.size();i++){
            if(userMapper.queryCampusById(roomIdList.get(i))==1){
                Hid.add(roomIdList.get(i));
            }else if(userMapper.queryCampusById(roomIdList.get(i))==2){
                Zid.add(roomIdList.get(i));
            }else if(userMapper.queryCampusById(roomIdList.get(i))==3){
                Tid.add(roomIdList.get(i));
            }
        }
        System.out.println("-------输出Zid-------");
        System.out.println(Zid);
        System.out.println(Zcount);
        int HarrCnt = 0,ZarrCnt=0,TarrCnt=0;
        for(int i=0;i<Hid.size();i++){
            Integer number = map2.get(Hid.get(i));
            HarrCnt+=number*valueMap.size();
        }
        for(int i=0;i<Zid.size();i++){
            Integer number = map2.get(Zid.get(i));
            ZarrCnt+=number*valueMap.size();
        }
        System.out.println(ZarrCnt);
        System.out.println("---------------------");
        for(int i=0;i<Tid.size();i++){
            Integer number = map2.get(Tid.get(i));
            TarrCnt+=number*valueMap.size();
        }
        //花津校区
        if(HarrCnt<=Hcount){
            for(int i=0;i<Hid.size();i++){
                Integer roomid = Hid.get(i);
                Integer number = map2.get(roomid);
                List<String> list = userMapper.queryERidBydate(arrangeParam.getExamData(), roomid);
                System.out.println("========list=========");
                System.out.println(list);
                int max=0;
                for(String s:list){
                    String lastTwo=s.substring(s.length()-2);
                    int num=Integer.parseInt(lastTwo);
                    if(num>max) max=num;
                }
                for(int j=0;j<valueMap.size();j++){
                    ERorder eRorder = new ERorder();
                    eRorder.setRoomId(roomid);
                    eRorder.setExamDate(date);
                    eRorder.setEnumber(number);
                    eRorder.setEtype(arrangeParam.getCourse());
                    List<String> strings = valueMap.get(j);
                    Date start = DateUtils.convertString2Date("HH:mm:ss", strings.get(0));
                    Date end = DateUtils.convertString2Date("HH:mm:ss", strings.get(1));
                    eRorder.setEstartTime(start);
                    eRorder.setEendTime(end);
                    String orderId="";
                    String x=String.format("%02d",roomid);
                    System.out.println("=========");
                    System.out.println(x);
                    if(list.size()==0){
                        String y=String.format("%02d",(j+1));
                        orderId=x+y;
                    }else {
                        String y=String.format("%02d",(max+j+1));
                        orderId=x+y;
                    }
                    eRorder.setEROrdId(orderId);
                    eRorderLists.add(eRorder);
                }
            }
        }else {
            Integer roomid = null;
            ArrayList<Integer> hlist1 = new ArrayList<>();
            ArrayList<Integer> hlist2 = new ArrayList<>();
            for(int i=0;i<Hid.size();i++){
                roomid = Hid.get(i);
                Integer number = map2.get(roomid);
                for(int j=0;j<valueMap.size();j++){
                    hlist1.add(roomid);
                    hlist2.add(number);
                }
            }
            System.out.println("------------hlist1和hlist2-----------");
            System.out.println(hlist1);
            System.out.println(hlist2);
            System.out.println("----------------------------------");
            List<String> list = userMapper.queryERidBydate(arrangeParam.getExamData(), roomid);
            System.out.println("========list=========");
            System.out.println(list);
            int max=0;
            for(String s:list){
                String lastTwo=s.substring(s.length()-2);
                int num=Integer.parseInt(lastTwo);
                if(num>max) max=num;
            }
            int Hsum=0,t=0;
            for(int i=0;i<hlist1.size();i++){
                Hsum+=hlist2.get(i);
                ERorder eRorder = new ERorder();
                eRorder.setRoomId(hlist1.get(i));
                eRorder.setExamDate(date);
                eRorder.setEtype(arrangeParam.getCourse());
                List<String> strings = valueMap.get(t);
                Date start = DateUtils.convertString2Date("HH:mm:ss", strings.get(0));
                Date end = DateUtils.convertString2Date("HH:mm:ss", strings.get(1));
                eRorder.setEstartTime(start);
                eRorder.setEendTime(end);

                String orderId="";
                String x=String.format("%02d",hlist1.get(i));
                if(list.size()==0){
                    String y=String.format("%02d",(t+1));
                    orderId=x+y;
                }else {
                    String y=String.format("%02d",(max+t+1));
                    orderId=x+y;
                }
                eRorder.setEROrdId(orderId);
                if(Hsum>Hcount){
                    eRorder.setEnumber(Hcount-(Hsum-hlist2.get(i)));
                    eRorderLists.add(eRorder);
                    break;
                }
                eRorder.setEnumber(hlist2.get(i));
                eRorderLists.add(eRorder);
                t++;
                if(t>=valueMap.size()) t=0;
            }
        }
        //赭山校区
        if(ZarrCnt<=Zcount){
            for(int i=0;i<Zid.size();i++){
                Integer roomid = Zid.get(i);
                Integer number = map2.get(roomid);
                for(int j=0;j<valueMap.size();j++){
                    ERorder eRorder = new ERorder();
                    eRorder.setRoomId(roomid);
                    eRorder.setExamDate(date);
                    eRorder.setEnumber(number);
                    eRorder.setEtype(arrangeParam.getCourse());
                    List<String> strings = valueMap.get(j);
                    Date start = DateUtils.convertString2Date("HH:mm:ss", strings.get(0));
                    Date end = DateUtils.convertString2Date("HH:mm:ss", strings.get(1));
                    eRorder.setEstartTime(start);
                    eRorder.setEendTime(end);
                    String orderId;
                    if(roomid<10){
                        orderId="0"+roomid+"0"+(j+1);
                    }else {
                        orderId=roomid+"0"+(j+1);
                    }
                    eRorder.setEROrdId(orderId);
                    eRorderLists.add(eRorder);
                }
            }
        }else {
            ArrayList<Integer> zlist1 = new ArrayList<>();
            ArrayList<Integer> zlist2 = new ArrayList<>();
            for(int i=0;i<Zid.size();i++){
                Integer roomid = Zid.get(i);
                Integer number = map2.get(roomid);
                for(int j=0;j<valueMap.size();j++){
                    zlist1.add(roomid);
                    zlist2.add(number);
                }
            }
            System.out.println("------------hlist1和hlist2-----------");
            System.out.println(zlist1);
            System.out.println(zlist2);
            System.out.println("----------------------------------");
            int Zsum=0,t=0;
            for(int i=0;i<zlist1.size();i++){
                Zsum+=zlist2.get(i);
                ERorder eRorder = new ERorder();
                eRorder.setRoomId(zlist1.get(i));
                eRorder.setExamDate(date);
                eRorder.setEtype(arrangeParam.getCourse());
                List<String> strings = valueMap.get(t);
                Date start = DateUtils.convertString2Date("HH:mm:ss", strings.get(0));
                Date end = DateUtils.convertString2Date("HH:mm:ss", strings.get(1));
                eRorder.setEstartTime(start);
                eRorder.setEendTime(end);
                String orderId;
                if(zlist1.get(i)<10){
                    orderId="0"+zlist1.get(i)+"0"+(t+1);
                }else {
                    orderId=zlist1.get(i)+"0"+(t+1);
                }
                eRorder.setEROrdId(orderId);
                if(Zsum>Zcount){
                    eRorder.setEnumber(Zcount-(Zsum-zlist2.get(i)));
                    eRorderLists.add(eRorder);
                    break;
                }
                eRorder.setEnumber(zlist2.get(i));
                eRorderLists.add(eRorder);
                t++;
                if(t>=valueMap.size()) t=0;
            }
        }
        //天门山校区
        if(TarrCnt<=Tcount){
            for(int i=0;i<Tid.size();i++){
                Integer roomid = Tid.get(i);
                Integer number = map2.get(roomid);
                for(int j=0;j<valueMap.size();j++){
                    ERorder eRorder = new ERorder();
                    eRorder.setRoomId(roomid);
                    eRorder.setExamDate(date);
                    eRorder.setEnumber(number);
                    eRorder.setEtype(arrangeParam.getCourse());
                    List<String> strings = valueMap.get(j);
                    Date start = DateUtils.convertString2Date("HH:mm:ss", strings.get(0));
                    Date end = DateUtils.convertString2Date("HH:mm:ss", strings.get(1));
                    eRorder.setEstartTime(start);
                    eRorder.setEendTime(end);
                    String orderId;
                    if(roomid<10){
                        orderId="0"+roomid+"0"+(j+1);
                    }else {
                        orderId=roomid+"0"+(j+1);
                    }
                    eRorder.setEROrdId(orderId);
                    eRorderLists.add(eRorder);
                }
            }
        }else {
            ArrayList<Integer> tlist1 = new ArrayList<>();
            ArrayList<Integer> tlist2 = new ArrayList<>();
            for(int i=0;i<Tid.size();i++){
                Integer roomid = Tid.get(i);
                Integer number = map2.get(roomid);
                for(int j=0;j<valueMap.size();j++){
                    tlist1.add(roomid);
                    tlist2.add(number);
                }
            }
            System.out.println("------------hlist1和hlist2-----------");
            System.out.println(tlist1);
            System.out.println(tlist2);
            System.out.println("----------------------------------");
            int Tsum=0,t=0;
            for(int i=0;i<tlist1.size();i++){
                Tsum+=tlist2.get(i);
                ERorder eRorder = new ERorder();
                eRorder.setRoomId(tlist1.get(i));
                eRorder.setExamDate(date);
                eRorder.setEtype(arrangeParam.getCourse());
                List<String> strings = valueMap.get(t);
                Date start = DateUtils.convertString2Date("HH:mm:ss", strings.get(0));
                Date end = DateUtils.convertString2Date("HH:mm:ss", strings.get(1));
                eRorder.setEstartTime(start);
                eRorder.setEendTime(end);
                String orderId;
                if(tlist1.get(i)<10){
                    orderId="0"+tlist1.get(i)+"0"+(t+1);
                }else {
                    orderId=tlist1.get(i)+"0"+(t+1);
                }
                eRorder.setEROrdId(orderId);
                if(Tsum>Tcount){
                    eRorder.setEnumber(Tcount-(Tsum-tlist2.get(i)));
                    eRorderLists.add(eRorder);
                    break;
                }
                eRorder.setEnumber(tlist2.get(i));
                eRorderLists.add(eRorder);
                t++;
                if(t>=valueMap.size()) t=0;
            }
        }

        System.out.println(eRorderLists);
        System.out.println("----------------");

        /**
         * 学生考试分布表
         */
        //从考场信息表中获取考场号和考场人数
        HashMap<Integer,String> map1H=new HashMap<>();
        HashMap<Integer,String> map1Z=new HashMap<>();
        HashMap<Integer,String> map1T=new HashMap<>();
        HashMap<Integer,Integer> map2H=new HashMap<>();
        HashMap<Integer,Integer> map2Z=new HashMap<>();
        HashMap<Integer,Integer> map2T=new HashMap<>();
        //每个校区所有考场可以安排多少人考试
        int countH=0,countZ=0,countT=0,h=0,z=0,t=0;
        for(int q=0;q<eRorderLists.size();q++){
            ERorder eRorder = eRorderLists.get(q);
            if(isCampus(eRorder.getRoomId())==1){
                map1H.put(h,eRorder.getEROrdId());
                map2H.put(h,eRorder.getEnumber());
                h++;
                countH+=eRorder.getEnumber();
            }
            if(isCampus(eRorder.getRoomId())==2) {
                map1Z.put(z,eRorder.getEROrdId());
                map2Z.put(z,eRorder.getEnumber());
                z++;
                countZ+=eRorder.getEnumber();
            }
            if(isCampus(eRorder.getRoomId())==3){
                map1T.put(t,eRorder.getEROrdId());
                map2T.put(t,eRorder.getEnumber());
                t++;
                countT+=eRorder.getEnumber();
            }
        }
        System.out.println(map1H);
        System.out.println(map2H);
        System.out.println("------------------");
        HashMap<Integer,String> map3H=new HashMap<>();
        HashMap<Integer,String> map3Z=new HashMap<>();
        HashMap<Integer,String> map3T=new HashMap<>();
        HashMap<Integer,Integer> map4H=new HashMap<>();
        HashMap<Integer,Integer> map4Z=new HashMap<>();
        HashMap<Integer,Integer> map4T=new HashMap<>();
        map3H.put(0,"0");map3Z.put(0,"0");map3T.put(0,"0");
        for(int a1=1;a1<=map1H.size();a1++){
            map3H.put(a1,map1H.get(a1-1));
        }
        for(int a1=1;a1<=map1Z.size();a1++){
            map3Z.put(a1,map1Z.get(a1-1));
        }
        for(int a1=1;a1<=map1T.size();a1++){
            map3T.put(a1,map1T.get(a1-1));
        }
        map4H.put(0,1);map4Z.put(0,1);map4T.put(0,1);
        for(int a2=1;a2<=map2H.size();a2++){
            int sun=1;
            for(int a3=0;a3<a2;a3++){
                sun+=map2H.get(a3);
            }
            map4H.put(a2,sun);
        }
        for(int a2=1;a2<=map2Z.size();a2++){
            int sun=1;
            for(int a3=0;a3<a2;a3++){
                sun+=map2Z.get(a3);
            }
            map4Z.put(a2,sun);
        }
        for(int a2=1;a2<=map2T.size();a2++){
            int sun=1;
            for(int a3=0;a3<a2;a3++){
                sun+=map2T.get(a3);
            }
            map4T.put(a2,sun);
        }
        System.out.println(map3H);
        System.out.println(map4H);
        //计算前端传递的这门课每个校区没有安排的人数
        int countStuH = userMapper.countStustate(arrangeParam.getCourse(), 0,1);
        int countStuZ = userMapper.countStustate(arrangeParam.getCourse(), 0,2);
        int countStuT = userMapper.countStustate(arrangeParam.getCourse(), 0,3);
        List<Student> stuH = userMapper.selectStuLimit(arrangeParam.getCourse(), 0, countH,1);
        List<Student> stuZ = userMapper.selectStuLimit(arrangeParam.getCourse(), 0, countZ,2);
        List<Student> stuT = userMapper.selectStuLimit(arrangeParam.getCourse(), 0, countT,3);
//        System.out.println("---------------------------");
//        for(Student student:stuH){
//            System.out.println(student);
//        }
        System.out.println("--------------------------------------------");
        System.out.println("countH:"+countH+",countStuH:"+countStuH);
        System.out.println("--------------------map4H-------------------");
        System.out.println(map4H);
        List<EStudent> eStudents=new ArrayList<>();
        //花津校区
        if(countStuH>=countH){
            for(int b=0;b<map4H.size()-1;b++){
                for(int b1=map4H.get(b);b1<=map4H.get(b+1)-1;b1++){
                    EStudent eStudent = new EStudent();
                    eStudent.setStuId(stuH.get(b1-1).getId());
                    eStudent.setStuName(stuH.get(b1-1).getName());
                    eStudent.setTeaName(stuH.get(b1-1).getTeacher());
                    eStudent.setClassId(stuH.get(b1-1).getZhuanye());
                    eStudent.setCourseId(stuH.get(b1-1).getCourseid());
                    eStudent.setEtype(stuH.get(b1-1).getXueke());
                    eStudent.setCampus(stuH.get(b1-1).getXiaoqu());
                    eStudent.setEROrdId(map3H.get(b+1));
                    eStudent.setExamId(stuH.get(b1-1).getId()+map3H.get(b+1));
                    eStudent.setExamDate(date);
                    eStudents.add(eStudent);
                }
            }
            int resultH = userMapper.updateState(0, countH, 1, arrangeParam.getCourse());
            System.out.println("花津校区"+resultH+"条学生考试安排成功！");
        }else {
            for(int b=0;b<map4H.size();b++){
                if(map4H.get(b)<=countStuH&&(map4H.get(b+1)-1)<=countStuH){
                    for(int b1=map4H.get(b);b1<=map4H.get(b+1)-1;b1++){
                        EStudent eStudent = new EStudent();
                        eStudent.setStuId(stuH.get(b1-1).getId());
                        eStudent.setStuName(stuH.get(b1-1).getName());
                        eStudent.setTeaName(stuH.get(b1-1).getTeacher());
                        eStudent.setClassId(stuH.get(b1-1).getZhuanye());
                        eStudent.setCourseId(stuH.get(b1-1).getCourseid());
                        eStudent.setEtype(stuH.get(b1-1).getXueke());
                        eStudent.setCampus(stuH.get(b1-1).getXiaoqu());
                        eStudent.setEROrdId(map3H.get(b+1));
                        eStudent.setExamId(stuH.get(b1-1).getId()+map3H.get(b+1));
                        eStudent.setExamDate(date);
                        eStudents.add(eStudent);
                    }
                }else {
                    for(int b1=map4H.get(b);b1<=countStuH;b1++){
                        EStudent eStudent = new EStudent();
                        eStudent.setStuId(stuH.get(b1-1).getId());
                        eStudent.setStuName(stuH.get(b1-1).getName());
                        eStudent.setTeaName(stuH.get(b1-1).getTeacher());
                        eStudent.setClassId(stuH.get(b1-1).getZhuanye());
                        eStudent.setCourseId(stuH.get(b1-1).getCourseid());
                        eStudent.setEtype(stuH.get(b1-1).getXueke());
                        eStudent.setCampus(stuH.get(b1-1).getXiaoqu());
                        eStudent.setEROrdId(map3H.get(b+1));
                        eStudent.setExamId(stuH.get(b1-1).getId()+map3H.get(b+1));
                        eStudent.setExamDate(date);
                        eStudents.add(eStudent);
                    }
                }
            }
            int resultH = userMapper.updateState(0, countStuH, 1, arrangeParam.getCourse());
            System.out.println("花津校区"+resultH+"条学生考试安排成功！");
        }

        System.out.println("--------------------------------------------");
        System.out.println("countZ:"+countZ+",countStuZ:"+countStuZ);
        System.out.println("--------------------map4Z-------------------");
        System.out.println(map4Z);

        //赭山校区
        if(countStuZ>=countZ){
            for(int b=0;b<map4Z.size()-1;b++){
                for(int b1=map4Z.get(b);b1<=map4Z.get(b+1)-1;b1++){
                    EStudent eStudent = new EStudent();
                    eStudent.setStuId(stuZ.get(b1-1).getId());
                    eStudent.setStuName(stuZ.get(b1-1).getName());
                    eStudent.setTeaName(stuZ.get(b1-1).getTeacher());
                    eStudent.setClassId(stuZ.get(b1-1).getZhuanye());
                    eStudent.setCourseId(stuZ.get(b1-1).getCourseid());
                    eStudent.setEtype(stuZ.get(b1-1).getXueke());
                    eStudent.setCampus(stuZ.get(b1-1).getXiaoqu());
                    eStudent.setEROrdId(map3Z.get(b+1));
                    eStudent.setExamId(stuZ.get(b1-1).getId()+map3Z.get(b+1));
                    eStudent.setExamDate(date);
                    eStudents.add(eStudent);
                }
            }
            int resultZ = userMapper.updateState(0, countZ, 2, arrangeParam.getCourse());
            System.out.println("赭山校区"+resultZ+"条学生考试安排成功！");
        }else {
            for(int b=0;b<map4Z.size();b++){
                if(map4Z.get(b)<=countStuZ&&(map4Z.get(b+1)-1)<=countStuZ){
                    for(int b1=map4Z.get(b);b1<=map4Z.get(b+1)-1;b1++){
                        EStudent eStudent = new EStudent();
                        eStudent.setStuId(stuZ.get(b1-1).getId());
                        eStudent.setStuName(stuZ.get(b1-1).getName());
                        eStudent.setTeaName(stuZ.get(b1-1).getTeacher());
                        eStudent.setClassId(stuZ.get(b1-1).getZhuanye());
                        eStudent.setCourseId(stuZ.get(b1-1).getCourseid());
                        eStudent.setEtype(stuZ.get(b1-1).getXueke());
                        eStudent.setCampus(stuZ.get(b1-1).getXiaoqu());
                        eStudent.setEROrdId(map3Z.get(b+1));
                        eStudent.setExamId(stuZ.get(b1-1).getId()+map3Z.get(b+1));
                        eStudent.setExamDate(date);
                        eStudents.add(eStudent);
                    }
                }else {
                    for(int b1=map4Z.get(b);b1<=countStuZ;b1++){
                        EStudent eStudent = new EStudent();
                        eStudent.setStuId(stuZ.get(b1-1).getId());
                        eStudent.setStuName(stuZ.get(b1-1).getName());
                        eStudent.setTeaName(stuZ.get(b1-1).getTeacher());
                        eStudent.setClassId(stuZ.get(b1-1).getZhuanye());
                        eStudent.setCourseId(stuZ.get(b1-1).getCourseid());
                        eStudent.setEtype(stuZ.get(b1-1).getXueke());
                        eStudent.setCampus(stuZ.get(b1-1).getXiaoqu());
                        eStudent.setEROrdId(map3Z.get(b+1));
                        eStudent.setExamId(stuZ.get(b1-1).getId()+map3Z.get(b+1));
                        eStudent.setExamDate(date);
                        eStudents.add(eStudent);
                    }
                }
            }
            int resultZ = userMapper.updateState(0, countStuZ, 2, arrangeParam.getCourse());
            System.out.println("赭山校区"+resultZ+"条学生考试安排成功！");
        }

        System.out.println("--------------------------------------------");
        System.out.println("countT:"+countT+",countStuT:"+countStuT);
        System.out.println("--------------------map4T-------------------");
        System.out.println(map4T);
        //天门山校区
        if(countStuT>=countT){
            for(int b=0;b<map4T.size()-1;b++){
                for(int b1=map4T.get(b);b1<=map4T.get(b+1)-1;b1++){
                    EStudent eStudent = new EStudent();
                    eStudent.setStuId(stuT.get(b1-1).getId());
                    eStudent.setStuName(stuT.get(b1-1).getName());
                    eStudent.setTeaName(stuT.get(b1-1).getTeacher());
                    eStudent.setClassId(stuT.get(b1-1).getZhuanye());
                    eStudent.setCourseId(stuT.get(b1-1).getCourseid());
                    eStudent.setEtype(stuT.get(b1-1).getXueke());
                    eStudent.setCampus(stuT.get(b1-1).getXiaoqu());
                    eStudent.setEROrdId(map3T.get(b+1));
                    eStudent.setExamId(stuT.get(b1-1).getId()+map3T.get(b+1));
                    eStudent.setExamDate(date);
                    eStudents.add(eStudent);
                }
            }
            int resultT = userMapper.updateState(0, countT, 3, arrangeParam.getCourse());
            System.out.println("天门山校区"+resultT+"条学生考试安排成功！");
        }else {
            for(int b=0;b<map4T.size();b++){
                if(map4T.get(b)<=countStuT&&(map4T.get(b+1)-1)<=countStuT){
                    for(int b1=map4T.get(b);b1<=map4T.get(b+1)-1;b1++){
                        EStudent eStudent = new EStudent();
                        eStudent.setStuId(stuT.get(b1-1).getId());
                        eStudent.setStuName(stuT.get(b1-1).getName());
                        eStudent.setTeaName(stuT.get(b1-1).getTeacher());
                        eStudent.setClassId(stuT.get(b1-1).getZhuanye());
                        eStudent.setCourseId(stuT.get(b1-1).getCourseid());
                        eStudent.setEtype(stuT.get(b1-1).getXueke());
                        eStudent.setCampus(stuT.get(b1-1).getXiaoqu());
                        eStudent.setEROrdId(map3T.get(b+1));
                        eStudent.setExamId(stuT.get(b1-1).getId()+map3T.get(b+1));
                        eStudent.setExamDate(date);
                        eStudents.add(eStudent);
                    }
                }else {
                    for(int b1=map4T.get(b);b1<=countStuT;b1++){
                        EStudent eStudent = new EStudent();
                        eStudent.setStuId(stuT.get(b1-1).getId());
                        eStudent.setStuName(stuT.get(b1-1).getName());
                        eStudent.setTeaName(stuT.get(b1-1).getTeacher());
                        eStudent.setClassId(stuT.get(b1-1).getZhuanye());
                        eStudent.setCourseId(stuT.get(b1-1).getCourseid());
                        eStudent.setEtype(stuT.get(b1-1).getXueke());
                        eStudent.setCampus(stuT.get(b1-1).getXiaoqu());
                        eStudent.setEROrdId(map3T.get(b+1));
                        eStudent.setExamId(stuT.get(b1-1).getId()+map3T.get(b+1));
                        eStudent.setExamDate(date);
                        eStudents.add(eStudent);
                    }
                }
            }
            int resultT = userMapper.updateState(0, countStuT, 3, arrangeParam.getCourse());
            System.out.println("天门山校区"+resultT+"条学生考试安排成功！");
        }

        System.out.println("-----------所有学生考试信息----------------");
        System.out.println(eStudents.size());
//        for(EStudent eStudent:eStudents){
//            System.out.println(eStudent);
//        }

        if(e==roomIdList.size()){
            int count=roomIdList.size()*valueMap.size();
            int result = userMapper.arrangerRoom(eRorderLists);
            int arrangeStu = userMapper.arrangeStu(eStudents);
            System.out.println("插入"+result+"条考场数据成功！");
            System.out.println("插入"+arrangeStu+"条学生考试信息成功！");
        }
        return new ArrayList<>();
    }

    @Override
    public void updateStu(String cname) {
        userMapper.updateStu(cname);
    }

    @Override
    public List<Integer> countStus(String cname) {
        return userMapper.countStus(cname);
    }

    @Override
    public List<Integer> countRooms() {
        return userMapper.countRooms();
    }

    @Override
    public List<Map<Object, Object>> selectIdDate(String cname) {
        return userMapper.selectIdDate(cname);
    }

    @Override
    public List<String> selectDate(String cname) {
        return userMapper.selectDate(cname);
    }

    @Override
    public List<Map<Object, Object>> selectRoomNumber(String cname, String times) {
        return userMapper.selectRoomNumber(cname,times);
    }

    @Override
    public List<String> selectCourse() {
        return userMapper.selectCourse();
    }

    @Override
    public List<OrderRoom> geteRoomList(eRoomQuery roomQuery) {
        return userMapper.geteRoomList(roomQuery);
    }

    @Override
    public Long counteRoomList(eRoomQuery roomQuery) {
        return userMapper.counteRoomList(roomQuery);
    }

    @Override
    public int deleteERooms(String ids) {
        return userMapper.deleteERooms(ids);
    }

    @Override
    public int deleteRoom() {
        userMapper.deleteRoom();
        int result = userMapper.countRoom();
        userMapper.deleteStuAll();
        userMapper.updateArrangeState();
        return result;
    }

    @Override
    public List<StuDetail> getStuArrangeDetail(eRoomQuery query) {
        return userMapper.getStuArrangeDetail(query);
    }

    @Override
    public Long countArrangeDetaile(eRoomQuery query) {
        return userMapper.countArrangeDetaile(query);
    }

    @Override
    public int deleteArrangeStu() {
        userMapper.deleteStuAll();
        int result = userMapper.countStuAll();
        userMapper.updateArrangeState();
        return result;
    }

    @Override
    public List<Student> selectUnState(String cname) {
        return userMapper.selectUnState(cname);
    }

    @Override
    public int individualArrange(InidivalArrange inidivalArrange) {
        //前端传来单独安排学生的学号字符串
        String students = inidivalArrange.getStudents();
        String[] strings = students.split("-");
        int stunumber=inidivalArrange.getStunumber();
        //根据机房地址获取机房号RoomId
        int roomid = userMapper.selectIdByName(inidivalArrange.getRoomaddr());
        System.out.println("roomid:"+roomid);
        //根据日期和机房获取所有考试时间段
        System.out.println("date:"+inidivalArrange.getExamData());
        List<Map<Object, Object>> mapList1 = userMapper.selectAllTime(inidivalArrange.getExamData(),roomid);
        for(int i=0;i<mapList1.size();i++){
            System.out.println(mapList1.get(i));
        }
        System.out.println("--------------");
        //获得开始时间
        Date start=DateUtils.convertString2Date("HH:mm:ss",inidivalArrange.getExamtime());
        //计算结束时间
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(start);
        calendar.add(Calendar.MINUTE,inidivalArrange.getDuration());
        Date end = calendar.getTime();
        System.out.println("start:"+start+" end:"+end);

        int flag=0,flag1=0;

        //人个人安排时间和erorder表中有重合
        for(int i=0;i<mapList1.size();i++){
            Map<Object, Object> map = mapList1.get(i);
            Date dbstart = DateUtils.convertString2Date("HH:mm:ss", String.valueOf(map.get("EstartTime")));
            Date dbend = DateUtils.convertString2Date("HH:mm:ss", String.valueOf(map.get("EendTime")));
            System.out.println("dbstart:"+dbstart+" dbend:"+dbend);
            if(start.getTime()==dbstart.getTime()&&end.getTime()==dbend.getTime()){
                flag=1;break;
            }
        }
        System.out.println("flag:"+flag);

        //个人安排时间和erorder表中有冲突重新安排
        for(int i=0;i<mapList1.size();i++){
            Map<Object, Object> map = mapList1.get(i);
            Date dbstart = DateUtils.convertString2Date("HH:mm:ss", String.valueOf(map.get("EstartTime")));
            Date dbend = DateUtils.convertString2Date("HH:mm:ss", String.valueOf(map.get("EendTime")));
            if(DateArrange.jiaoji(dbstart,dbend,start,end)==1){
                flag1=1;break;
            }
        }
        System.out.println("flag1:"+flag1);

        //前端传递的时间段与查询的某一个时间段重合，则不用在erorder表中插入数据
        if(flag==1){
            System.out.println("时间段重合");
            //查找这个时间段的考生人数和本场考试可以考试的人数比较，前者小于后者可以插入，前者等于后者不能插入
            //查找考场编号EROrdId
            String id = userMapper.selectIdByTime(inidivalArrange.getExamData(), DateUtils.convertDate2String("HH:mm:ss",start), DateUtils.convertDate2String("HH:mm:ss",end), roomid);
           //本场考试人数（estudent表中安排本场考试人数）
            Integer cnt = userMapper.selectCntByIdDate(inidivalArrange.getExamData(), id);
            //本场考试容量人数（erorder中的Enumber）
            Integer num = userMapper.selectNumByTime(inidivalArrange.getExamData(), DateUtils.convertDate2String("HH:mm:ss", start), DateUtils.convertDate2String("HH:mm:ss", end), roomid);
            int cnt1 = userMapper.cntByName(inidivalArrange.getRoomaddr());
            if(inidivalArrange.getStunumber()+cnt>cnt1){
                //单独安排的人数和已安排人数超过考场可以考试人数，不能插入
                return 1;
            }else {
                //将单独安排的人插入esudent表中
                List<EStudent> eStudents=new ArrayList<>();
                for(String s:strings){
                    EStudent eStudent = new EStudent();
                    String[] s1 = s.split(" ");
                    eStudent.setStuId(s1[0]);
                    eStudent.setStuName(s1[1]);
                    Student student = userMapper.SelectStuByIdCname(s1[0], inidivalArrange.getCourses());
                    eStudent.setStuName(student.getName());
                    eStudent.setCampus(student.getXiaoqu());
                    eStudent.setEtype(student.getXueke());
                    eStudent.setTeaName(student.getTeacher());
                    eStudent.setClassId(student.getZhuanye());
                    eStudent.setCourseId(student.getCourseid());
                    eStudent.setEROrdId(id);
                    eStudent.setExamDate(DateUtils.convertString2Date("yyyy-MM-dd",inidivalArrange.getExamData()));
                    eStudent.setExamId(s1[0]+id);
                    eStudents.add(eStudent);
                    userMapper.updateStateByIdCourse(s1[0],inidivalArrange.getCourses());
                }
                System.out.println(eStudents);
                userMapper.arrangeStu(eStudents);
                return 2; //可以插入(时间段重合直接可以插入学生)
            }
        }

        //前端传递的时间段与查询是时间段有交集
        if(flag1==1){
            System.out.println("存在交集");
            return -1; //时间段存在交集不能插入
        }

        //插入eorder考场时间
//        if(flag1==0&&flag==0){
//            System.out.println("插入");
            //插入eorder表考场时间
            String a="",b="";
            List<ERorder> eRorders=new ArrayList<>();
            ERorder eRorder=new ERorder();
            eRorder.setExamDate(DateUtils.convertString2Date("yyyy-MM-dd",inidivalArrange.getExamData()));
            eRorder.setEstartTime(start);
            eRorder.setEendTime(end);
            eRorder.setEtype(inidivalArrange.getCourses());
            eRorder.setRoomId(roomid);
            Room roomById = userMapper.getRoomById(roomid);
            eRorder.setEnumber(stunumber);
            Integer integer = userMapper.cntByIdDateName(roomid, inidivalArrange.getCourses(), inidivalArrange.getExamData());
            if(roomid<10){
                a="0"+roomid;
            }else {
                a=""+roomid;
            }
            if(integer<10){
                b="0"+(integer+1);
            }else {
                b=""+(integer+1);
            }
            eRorder.setEROrdId(a+b);
            eRorders.add(eRorder);
            List<EStudent> eStudents1=new ArrayList<>();
            for(String s:strings){
                EStudent eStudent = new EStudent();
                String[] s1 = s.split(" ");
                eStudent.setStuId(s1[0]);
                eStudent.setStuName(s1[1]);
                Student student = userMapper.SelectStuByIdCname(s1[0], inidivalArrange.getCourses());
                eStudent.setStuName(student.getName());
                eStudent.setCampus(student.getXiaoqu());
                eStudent.setEtype(student.getXueke());
                eStudent.setTeaName(student.getTeacher());
                eStudent.setClassId(student.getZhuanye());
                eStudent.setCourseId(student.getCourseid());
                eStudent.setEROrdId(a+b);
                eStudent.setExamDate(DateUtils.convertString2Date("yyyy-MM-dd",inidivalArrange.getExamData()));
                eStudent.setExamId(s1[0]+a+b);
                eStudents1.add(eStudent);
                userMapper.updateStateByIdCourse(s1[0],inidivalArrange.getCourses());
            }
            System.out.println(eRorders);
            System.out.println(eStudents1);
            userMapper.arrangerRoom(eRorders);
            userMapper.arrangeStu(eStudents1);
            return 3; //可以插入（时间段和学生同时插入）
//        }
//        return 0;
    }

    @Override
    public List<ERorder> selectERorderByRoomAddr(String cname, String roomAddr) {
        //查找机房号
//        int roomid = userMapper.selectIdByName(roomAddr);
//        System.out.println("UserServiceImpl:"+cname+" "+roomAddr);
        Integer roomid = userMapper.selectIdByName(roomAddr);
//        System.out.println("roomid:"+roomid);
        List<ERorder> eRorderList = userMapper.selectERorderByRoomAddr(cname, roomid);
//        System.out.println("UserServiceImpl:"+eRorderList);
        return eRorderList;
    }

    @Override
    public List<EStudent> selectByIdDate(String cname, String EROrdId, String ExamDate) {
        //将课程名转换成课程编号
        String cIdByCname = userMapper.selectCIdByCname(cname);
        List<EStudent> eStudents = userMapper.selectByIdDate(cIdByCname, EROrdId, ExamDate);
        return eStudents;
    }

    @Override
    public int deleteStusById(String ids, String cname) {
        String cIdByCname = userMapper.selectCIdByCname(cname);
        int i = userMapper.deleteStusById(ids, cIdByCname);
        return i;
    }

    @Override
    public int updatanumber(String cname, String erordId, String examDate, int cnt) {
        return userMapper.updatanumber(cname,erordId,examDate,cnt);
    }

    @Override
    public int updateStateByIdCourse2(String ids, String cname) {
        return userMapper.updateStateByIdCourse2(ids,cname);
    }

    @Override
    public int deleteerorder(String erorder, String examdate, String cname) {
        return userMapper.deleteerorder(erorder,examdate,cname);
    }

    @Override
    public int deleteStudents(String erorder, String examdate, String cname) {
        String cIdByCname = userMapper.selectCIdByCname(cname);
        int i = userMapper.deleteStudents(erorder, examdate, cIdByCname);
        return i;
    }

    @Override
    public int cntByName(String name) {
        return userMapper.cntByName(name);
    }

    @Override
    public List<StuDetail> selectAllestudent() {
        return userMapper.selectAllestudent();
    }

    @Override
    public List<OrderRoom> selectAllRoom() {
        return userMapper.selectAllRoom();
    }

    @Override
    public int changeStus(String course, String leftroom, String rightroom, String rightStr,int leftnumbers,int rightnumbers) {
        //删除原有考场信息
        String courseid = userMapper.selectCIdByCname(course); //课程名查找课程号
        //第几场考试
        String lerord = leftroom.split("     ")[0];
        String rerord = rightroom.split("     ")[0];
        //考试日期
        String lexandate = leftroom.split("     ")[1];
        String rexandate = rightroom.split("     ")[1];
        int result = userMapper.deleteLeftStu(rightStr, courseid, lerord, lexandate);
        //原来考场人数减少
        userMapper.setnumber(course,lerord,lexandate,leftnumbers);
        userMapper.setnumber(course,rerord,rexandate,rightnumbers);
        //增加新考场信息
        List<EStudent> eStudents = new ArrayList<>();
        String[] split = rightStr.split(",");
        for(int i=0;i<split.length;i++){
            Student student = userMapper.SelectStuByIdCname(split[i], course);
            EStudent eStudent=new EStudent();
            eStudent.setExamId(split[i]+rerord);
            eStudent.setStuId(split[i]);
            eStudent.setStuName(student.getName());
            eStudent.setCampus(student.getXiaoqu());
            eStudent.setEtype(student.getXueke());
            eStudent.setTeaName(student.getTeacher());
            eStudent.setClassId(student.getZhuanye());
            eStudent.setCourseId(courseid);
            eStudent.setEROrdId(rerord);
            eStudent.setExamDate(DateUtils.convertString2Date("yyyy-MM-dd",rexandate));
            eStudents.add(eStudent);
        }
        int result2= userMapper.arrangeStu(eStudents);
        return result==result2?1:0;
    }

    @Override
    public int selectroomByname(String name) {
        return userMapper.selectIdByName(name);
    }

    @Override
    public List<ERorder> queryAllById(int id) {
        List<ERorder> eRorderList = userMapper.selectERorderByRoomid(id);
        return eRorderList;
    }

    @Override
    public List<String> queryIDS(String erorder, String examDate, String cname) {
        String cIdByCname = userMapper.selectCIdByCname(cname);
        return userMapper.queryIDS(erorder, examDate, cIdByCname);
    }

    @Override
    public Admin login(Admin admin) {
        return userMapper.adminlogin(admin);
    }

    @Override
    public int selectByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    public int inseruser(String username, String password) {
        return userMapper.inseruser(username,password);
    }

    @Override
    public List<StuDetail> showRoomStu(String examDate, String order, String etype) {
        List<StuDetail> stuDetails = userMapper.showStuByexam(examDate, order, etype);
        return stuDetails;
    }
}
